package com.example.demo2.controller;

import com.example.demo2.entity.*;
import com.example.demo2.mapper.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@CrossOrigin
public class SolutionController {
    // 获取当前工作目录的File对象
    File userDir = new File(System.getProperty("user.dir"));

    // 获取父目录的File对象，即D:/idea/
    File parentDir = userDir.getParentFile();

    // 再次获取上一级目录的File对象，即D:/
    File grandParentDir = parentDir.getParentFile();

    // 现在grandParentDir指向D:/，我们想在D:/下创建file目录
    // 因此，我们创建一个新的File对象指向D:/file
    File fileDir = new File(grandParentDir, "file");

    // 将fileDir转换为绝对路径
    String ROOT_PATH = fileDir.getAbsolutePath();
    @Autowired
    SolutionMapper solutionMapper;


    @RequestMapping("/getAllSolutionsOfEqu")
    public List<Solution> getAllSolutionsOfEquById(@RequestParam int eid)
    {
        return solutionMapper.getAllSolutionsOfEquById(eid);
    }

    @PostMapping("/modifySolution")
    public int modifySolution(@RequestBody Solution solution)
    {
        String factory = solution.getFactory();
        String picture = solution.getPicture();
        //String describe = solution.getDescribe();
        String soName = solution.getSoName();
        String soUrl = solution.getSoUrl();
        int soId = solution.getSoId();

        Solution solution1 = new Solution();

        solution1.setFactory(factory);
        solution1.setPicture(picture);
        //solution1.setDescribe(describe);
        solution1.setSoName(soName);
        solution1.setSoUrl(soUrl);
        solution1.setSoId(soId);

        return solutionMapper.modifySolution(solution1);
    }

    @PutMapping("/addSolution")
    public int addSolution(@RequestBody Solution solution)
    {

        int eId = solution.geteId();
        String factory = solution.getFactory();
        String picture = solution.getPicture();
        //String describe = solution.getDescribe();
        String soName = solution.getSoName();
        String soUrl = solution.getSoUrl();

        Solution solution1 = new Solution();

        solution1.setFactory(factory);
        solution1.setPicture(picture);
        //solution1.setDescribe(describe);
        solution1.setSoName(soName);
        solution1.setSoUrl(soUrl);
        solution1.seteId(eId);

        return solutionMapper.addSolution(solution1);
    }


    private String uploadFile(MultipartFile file, String fileType) {
        if (file.isEmpty()) {
            return null;
        }
        try {
            // 根据fileType确定存放目录
            String uploadDir = "D://registerphoto/" + fileType + "/";

            // 用时间戳+原始文件名确保文件名唯一性
            String originalFilename = file.getOriginalFilename();
            String fileName = System.currentTimeMillis() + "_" + originalFilename;
            File destFile = new File(uploadDir + fileName);

            // 创建目录，如果不存在则创建
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            // 保存文件到本地
            file.transferTo(destFile);

            // 生成文件访问URL（此处需根据实际情况修改。例如静态资源映射到 /files/**）
            String fileUrl = "http://localhost:8081/files/" + fileType + "/" + fileName;
            return fileUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传图片并在数据库中添加solution记录
     * 假设需要从前端获取 eId, factory, describe, soName 等信息
     */
    @PostMapping("/uploadPicture")
    public ResponseEntity<String> uploadPicture(
            @RequestParam("file") MultipartFile file,
            @RequestParam("eId") Integer eId,
            @RequestParam("factory") String factory,
            @RequestParam("describe") String describe,
            @RequestParam("soName") String soName
    ) {
        String fileType = "images"; // 固定为images类型
        String fileUrl = uploadFile(file, fileType);
        if (fileUrl == null) {
            return ResponseEntity.badRequest().body("文件上传失败，请检查文件是否为空或服务器配置");
        }

        // 构建Solution对象
        Solution solution = new Solution();
        solution.seteId(eId);
        solution.setFactory(factory);
        // 此处假设picture字段为图片路径或名称，这里可以直接用fileUrl，如果需要仅存文件名，则需要自行截取
        solution.setPicture(fileUrl);
        solution.setDescribe(describe);
        solution.setSoName(soName);
        solution.setSoUrl(fileUrl); // 若soUrl需要存储文件URL则直接使用

        int result = solutionMapper.addSolution(solution);
        if (result > 0) {
            return ResponseEntity.ok("文件上传并添加solution成功：" + fileUrl);
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传成功，但数据库插入失败");
        }
    }




    @DeleteMapping("/deleteSoluListOfEqu")
    public int deleteSoluListOfEqu(@RequestBody List<Integer> soids)
    {

        //String eids = eIds.stream().map(String::valueOf).collect(Collectors.joining(","));

        return solutionMapper.deleteSoluListOfEqu(soids);
    }

//    @PostMapping("/uploadPicture111")
//    public ResponseEntity<ApiResponse<String>> uploadPicture(@RequestParam("file") MultipartFile file) throws IOException {
//        if (file.isEmpty()) {
//            return ResponseEntity.badRequest().body(
//                    new ApiResponse<>(400, null, "Empty file")
//            );
//        }
//
//        System.out.println("555555555555555555555555555555"+"调用上传图片");
//
//        try {
//            String originalFilename = file.getOriginalFilename();
//            String filename = UUID.randomUUID().toString() +
//                    originalFilename.substring(originalFilename.lastIndexOf("."));
//
//            // 修改为静态资源目录
//            Path path = Paths.get("C:\\Users\\86181\\Desktop\\final_xm\\front(zc)\\medical_project(支持人员前端完成\\font\\medical-project\\src\\assets\\soluimages", filename);
//            Files.createDirectories(path.getParent());
//            Files.write(path, file.getBytes());
//
//            // 返回HTTP可访问的URL
//            //String fileUrl = "http://localhost:8081/uploads/" + filename;
//
//            return ResponseEntity.ok(
//                    new ApiResponse<>(200, filename, "上传成功")
//            );
//        } catch (IOException e) {
//            return ResponseEntity.status(500).body(
//                    new ApiResponse<>(500, null, "上传失败：" + e.getMessage())
//            );
//        }
//    }
//
//    @PostMapping("/uploadPDF")
//    public ResponseEntity<ApiResponse<String>> uploadPDF(@RequestParam("file") MultipartFile file) throws IOException {
//        if (file.isEmpty()) {
//            return ResponseEntity.badRequest().body(
//                    new ApiResponse<>(400, null, "Empty file")
//            );
//        }
//
//        System.out.println("555555555555555555555555555555"+"调用上传pdf");
//        try {
//            String originalFilename = file.getOriginalFilename();
//            String filename = UUID.randomUUID().toString() +
//                    originalFilename.substring(originalFilename.lastIndexOf("."));
//
//            // 修改为静态资源目录
//            Path path = Paths.get("C:\\Users\\86181\\Desktop\\final_xm\\front(zc)\\medical_project(支持人员前端完成\\font\\medical-project\\src\\assets\\pdfs", filename);
//            Files.createDirectories(path.getParent());
//            Files.write(path, file.getBytes());
//
//            // 返回HTTP可访问的URL
//            //String fileUrl = "http://localhost:8081/uploads/" + filename;
//
//            return ResponseEntity.ok(
//                    new ApiResponse<>(200, filename, "上传成功")
//            );
//        } catch (IOException e) {
//            return ResponseEntity.status(500).body(
//                    new ApiResponse<>(500, null, "上传失败：" + e.getMessage())
//            );
//        }
//    }
@PostMapping("/uploadSoluFile")
public ResponseEntity<ApiResponse<String>> uploadPicture(@RequestParam("file") MultipartFile file,
                                                         @RequestParam("fileType") String fileType) throws IOException {
    if (file.isEmpty()) {
        return ResponseEntity.badRequest().body(
                new ApiResponse<>(400, null, "Empty file")
        );
    }
    System.out.println("555555555555555555555555555555"+"调用上传图片");
    String originalFilename = file.getOriginalFilename();
    String filename = UUID.randomUUID().toString() +
            originalFilename.substring(originalFilename.lastIndexOf("."));

    String subFolder = fileType.equals("image") ? "images" : "pdfs";

    File destFile = new File(ROOT_PATH + File.separator + subFolder + File.separator + filename);

    if(!destFile.getParentFile().exists())
    {
        destFile.getParentFile().mkdirs();
    }

    file.transferTo(destFile);

    //Files.write(destFile, file.getBytes());
    // 返回HTTP可访问的URL
    String fileUrl = "http://localhost:8081/files/" + subFolder + "/" + filename;

    return ResponseEntity.ok(
            new ApiResponse<>(200, fileUrl, "上传成功")
    );
}

}
